//
//  WMImagePickerController.swift
//  WMToolsDemo
//
//  Created by WTFSSD on 2016/12/14.
//  Copyright © 2016年 WTFSSD. All rights reserved.
//

import Foundation
import UIKit
import AssetsLibrary
class WMImagePickerController: UIViewController {
    let mm = PhotoManager.shareManager
    
    lazy var scrollView: UIScrollView = {
        let sv = UIScrollView.init(frame: self.view.bounds)
        return sv
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        view.addSubview(scrollView)
        PhotoManager.openAllImages({ (imags) in
                dispatch_async(dispatch_get_main_queue(), {
                    self.layoutImages(imags)
                })
            }) { (error) in

        }
        
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func layoutImages(imgs : [UIImage]) -> Void {
        let rows = imgs.count/3
        let lrows = imgs.count%3
        let space = CGFloat(10);
        let width = (view.frame.width - 4 * space)/3
        let height = width * 1.1
        for index in 0..<imgs.count {
            let rrr = index / 3
            let ccc = index % 3
            let x = CGFloat(ccc) * (width + space) + space
            let y = CGFloat(rrr) * (height + space) + space
            let imgv = UIImageView.init(image: imgs[index])
            imgv.frame = CGRectMake(x,y , width, height)
            scrollView.addSubview(imgv)
        }
        let sh = CGFloat(rows) * (space + height) + CGFloat(lrows == 0 ? 0 : CGFloat(space + height))
        scrollView.contentSize = CGSizeMake(view.frame.width, sh)
    }
    
}


typealias GroupBlock = ([ALAssetsGroup])->Void
typealias CameraRollHandle = ()->Void


class PhotoManager: AnyObject {
    static let shareManager = PhotoManager()
    var groups:[ALAssetsGroup] = []
    var photos:[AnyObject] = []
    let library = ALAssetsLibrary.init()
    var groupBlock : GroupBlock?
    var cameraRollHandle : CameraRollHandle?
    func readAllGroups(success:GroupBlock,failBlock:ALAssetsLibraryAccessFailureBlock) -> Void {
        groups.removeAll()
        library.enumerateGroupsWithTypes(ALAssetsGroupAll, usingBlock: { (group, pd) in
            if (group != nil) {
                group.setAssetsFilter(ALAssetsFilter.allPhotos())
                self.groups.append(group)
                if self.containCameraRoll(group) {
                    self.groups.removeAtIndex(self.groups.count - 1)
                    self.groups.insert(group, atIndex: 0)
                    if self.cameraRollHandle != nil{
                        self.cameraRollHandle!()
                    }
                }
                success(self.groups)
            }
            }) { (error) in
            failBlock(error)
        }
    }
    
    func containCameraRoll(group:ALAssetsGroup) -> Bool {
      let nameEN =   NSLocalizedString(group.valueForProperty(ALAssetsGroupPropertyName) as! String, comment: "")
      let nameCN =   NSLocalizedString(group.valueForProperty(ALAssetsGroupPropertyName) as! String, comment: "")
        if nameEN == "相机胶卷" || nameCN == "Camera Roll" {
            return true
        }
        return false
    }
   
    func openGroup(group:ALAssetsGroup,success:([UIImage] ->Void),faileBlock:ALAssetsLibraryAccessFailureBlock) -> Void{
        
        let url = group.valueForProperty(ALAssetsGroupPropertyURL) as! NSURL
        var images : [UIImage] = []
        library.groupForURL(url, resultBlock: { (g) in
            g.enumerateAssetsUsingBlock({ (result, index, pb) in
                if result != nil && result.valueForProperty(ALAssetPropertyType) as! String == ALAssetTypePhoto {
                    let cgimg:CGImage = result.aspectRatioThumbnail().takeUnretainedValue()
                    let img = UIImage.init(CGImage: cgimg)
                    images.append(img)
                    if index == g.numberOfAssets() - 1 {
                        success(images)
                    }
                }
            })
            }) { (error) in
                faileBlock(error)
        }
    }
    
    
   class func openAllImages(successCallBack:([UIImage]->Void),faile:ALAssetsLibraryAccessFailureBlock) -> Void {
        let manager = self.shareManager
        var images : [UIImage] = []
        var index = 0
        manager.readAllGroups({ (grps) in
            
            for g in grps{
                manager.openGroup(g, success: { (arrs) in
                    images.appendContentsOf(arrs)
                    index += 1
//                    print(index,arrs.count,images.count)
                    if index == grps.count-1 {
                        print("--->",arrs.count,images.count)
                       successCallBack(images)
                    }
                    }, faileBlock: { (err) in
                        faile(err)
                })
            }
        }) { (error) in
            faile(error);
    }
    }
}
